package cn.itlaobing.web.filter;

import javax.servlet.*;
import javax.servlet.Filter;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class AllFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req=null;
        HttpServletResponse resp=null;
        if(request instanceof HttpServletRequest){
            req=(HttpServletRequest)request;
        }
        if(response instanceof  HttpServletResponse){
            resp=(HttpServletResponse)response;
        }
        //设置字符集
        req.setCharacterEncoding("utf-8");
        //放行登录界面
        String url=req.getRequestURI();
        if(url.startsWith("/assets")||"/servlet/index".equals(url)||"/index.jsp".equals(url)||"/servlet/regection".equals(url)){
            chain.doFilter(req,resp);
        }else{
            if(req.getSession().getAttribute("USER")==null){
                resp.sendRedirect("/servlet/index");
                return;
            }else{
                chain.doFilter(req,resp);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
